<?php

namespace app\common\controller;

use think\Controller;
use think\facade\Session;

class AdminBaseController extends Controller {

    /**
     * 验证失败直接抛出异常
     * @var bool
     */
    protected $failException = true;
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];
    /**
     * 需要鉴权的方法,但需要登录
     * @var array
     */
    protected $needRight = [];
    /**
     * 不允许操作的方法
     * @var array
     */
    protected $noNeedView = [];
    /**
     * 模型对象
     * @var \think\Model
     */
    protected $model = null;
    /**
     * 登录对象 platform admin
     * @var null
     */
    protected $sessionKey = null;
    /**
     * 员工登录信息
     * @var null
     */
    protected $loginInfo = null;
    /**
     * 追加查询条件
     * @var array
     */
    protected $appendQuery = ['site_id','trade_id'];
    /**
     * 追加用户字段
     */
    protected $appendUserFields = ['site_id','trade_id'];

    /**
     * 初始化方法
     * AdminBaseController constructor.
     */
    public function __construct() {
        parent::__construct();
        $actionName = strtolower($this->request->action());
        if(!Session::has('session_key')){
            $this->error('登录对象不明确！',url('Public/login'));
        }
        $this->sessionKey = Session::get('session_key');
        $this->loginInfo = Session::get($this->sessionKey);
        if(in_array($actionName, $this->noNeedView)){
            if($this->request->isAjax()){
                $this->error('抱歉...该方法不允许操作！');
            }else{
                return $this->redirect('/error',['type'=>'2']);
            }
        }
        $auth = \org\Auth::instance('admin');
        //排除无需登录方法
        if (!in_array($actionName, $this->noNeedLogin)) {
            //是否登录
            if (!$this->isLogin()) {
                $this->error('请登录后再操作!', url('Public/login'));
            }
            //是否鉴权
            if (in_array($actionName, $this->needRight)) {
                if (!$auth->check($this->request->url(), $this->loginInfo['id'])) {
                    if($this->request->isAjax()){
                        $this->error('你没有该操作权限！');
                    }else{
                        return $this->redirect('/error');
                    }
                }
            }
        }
        $this->assign('auth', $auth);
        $this->assign('sessionKey', $this->sessionKey);
        $this->assign('loginInfo', $this->loginInfo);
    }

    /**
     * 是否登录
     * @return bool
     */
    public function isLogin() {
        if(!Session::has($this->sessionKey)) return false;
        if($this->sessionKey == 'site'){
            if((int)$this->loginInfo['site_id']<=0 || (int)$this->loginInfo['group_id']<=0){
                return false;
            }
        }
        if($this->sessionKey == 'platform'){
            if((int)$this->loginInfo['site_id']>0){
                return false;
            }
        }
        return true;
    }

}
